import 'package:flutter/material.dart';

import '../../../utils/basic_value_wrappers.dart';
import '../../../app_options/colors.dart';

class CheckboxOption extends StatefulWidget {
  const CheckboxOption(
      {super.key,
      required this.value,
      required this.labelText,
      this.onChanged,
      this.labelStyle,
      this.isWholeLine = false,
      this.tristate = false,
      this.enabledNotifier});

  final String labelText;
  final ValueChanged<bool?>? onChanged;
  final bool tristate;
  final TextStyle? labelStyle;
  final bool isWholeLine;
  final BoolValue value;

  final ValueNotifier<bool>? enabledNotifier;
  @override
  State<StatefulWidget> createState() => _CheckboxOptionState();
}

class _CheckboxOptionState extends State<CheckboxOption> {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
      builder: (context, enabled, child) {
        TextStyle? labelStyle = widget.labelStyle;
        if (enabled == false) {
          labelStyle = labelStyle != null
              ? labelStyle.copyWith(color: disabledColor)
              : const TextStyle(color: disabledColor);
        }

        List<Widget> checkboxItems = [
          SizedBox(
            width: 32,
            height: 32,
            child: Checkbox(
              value: widget.value.value,
              tristate: widget.tristate,
              onChanged: enabled == false
                  ? null
                  : ((value) {
                      setState(() {
                        widget.value.value = !widget.value.value!;
                      });
                      if (widget.onChanged != null) {
                        widget.onChanged!(value);
                      }
                    }),
            ),
          ),
          Text(widget.labelText, style: labelStyle)
        ];

        return InkWell(
          onTap: enabled
              ? () {
                  //TODO::对于tristate的支持不太合理
                  widget.value.value ??= false;

                  setState(() {
                    widget.value.value = !widget.value.value!;
                  });
                }
              : null,
          child: widget.isWholeLine == false
              ? Wrap(
                  crossAxisAlignment: WrapCrossAlignment.center,
                  children: checkboxItems)
              : Row(children: checkboxItems),
        );
      },
      valueListenable: widget.enabledNotifier ?? ValueNotifier<bool>(true),
    );
  }
}
